using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Text;
using System.Windows.Forms;
using System.Threading;
using Mud.Common;
using Mud.Common.GUI;

namespace Mud.Server
{
	public partial class frmMain : Form
	{
		private Server _server;
		private Client.RemoteClientServer _clientServer;
		private Thread _serverThread;
		private bool _serverRunning;

		public frmMain() {
			InitializeComponent();
			Logger.AddSink(txtLog);
			Logger.AddSink(new FileLogSink(LogType.LogSeverity.All ^ LogType.LogSeverity.Debug2));
		}

		protected override void OnClosing(CancelEventArgs e) {
			if (_serverRunning)
				StopServer();
			Logger.ClearSinks();
		}

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);
			System.Drawing.Rectangle screenBounds = Screen.GetWorkingArea(this);
            this.Bounds = new System.Drawing.Rectangle(0, screenBounds.Bottom - 200, screenBounds.Width, 200);
			StartServer();
		}

		private void tsbStartStopServer_Click(object sender, EventArgs e) {
			if (!_serverRunning)
				StartServer();
			else
				StopServer();
		}

		private void StartServer() {
			_server = new Server();
			_clientServer = new Client.RemoteClientServer(_server);
			_clientServer.RemoteServerClientAdded += new Client.RemoteClientServer.RemoteServerClientHandler(_clientServer_RemoteServerClientAdded);
			ParameterizedThreadStart start = new ParameterizedThreadStart(StartServerThread);
			_serverThread = new Thread(start);
			_serverThread.Start(_server);
			_serverRunning = true;
			this.Text = String.Format("Server '{0}' running.", _server.CurrentConfiguration.ServerName);
			tsbStartStopServer.Text = "Stop server";
			_clientServer.Start();

		}

		void _clientServer_RemoteServerClientAdded(Mud.Server.Client.RemoteServerClient client)
		{
			_server.AddClient(client);
		}

		private void StopServer() {
			if (_server == null)
				return;

			_clientServer.Stop();
			_server.Stop();
			if (_serverThread.IsAlive)
				_serverThread.Join();
			_serverRunning = false;
			tsbStartStopServer.Text = "Start server";
			this.Text = "Server stopped";
			_server = null;
		}

		private void StartServerThread(object data) {
			Server server = (Server)data;
			System.Threading.Thread.CurrentThread.Name = "Server";
			server.Start();
			this.BeginInvoke(new AsyncMethodCall(StopServer));
		}

		private delegate void AsyncMethodCall();

        private void tsbTail_Click(object sender, EventArgs e)
        {

            System.Diagnostics.Process.Start("..\\..\\TailMe\\TailMe.exe");
        }

	}
}